from typing import *

from . import db


def create_conn():
    conn = db.get_sql_client()
    # cursor = conn.cursor(pymysql.cursors.DictCursor)
    cursor = conn.cursor()
    return conn, cursor


def close_conn(conn, cursor):
    cursor.close()
    conn.close()


def select_one(sql, args):
    conn, cur = create_conn()
    cur.execute(sql, args)
    result = cur.fetchone()
    close_conn(conn, cur)
    return result


def executescript(sql: str) -> NoReturn:
    conn, cur = create_conn()
    cur.executescript(sql)
    close_conn(conn, cur)
    return


def select_all(sql, *args, **kwargs):
    conn, cur = create_conn()
    cur.execute(sql, *args, **kwargs)
    result = cur.fetchall()
    close_conn(conn, cur)
    return result


def insert_one(sql, args):
    conn, cur = create_conn()
    result = cur.execute(sql, args)
    conn.commit()
    close_conn(conn, cur)
    return result


def delete_one(sql, args):
    conn, cur = create_conn()
    result = cur.execute(sql, args)
    conn.commit()
    close_conn(conn, cur)
    return result


def update_one(sql, args):
    conn, cur = create_conn()
    result = cur.execute(sql, args)
    conn.commit()
    close_conn(conn, cur)
    return result


def table_exists(tbl_name: str) -> bool:
    sql = f"select 1 from {tbl_name} limit 1"
    try:
        rs = select_one(sql, None)
        return rs is None
    except Exception:
        return False
